import {
	NetService
} from '../../common/NetService';
/*var jweixin = require('jweixin-module')*/
export default {
	data() {
		return {
			address: "",
			indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth / (750 / 100))}px;`,
			valueArr: [0, 0, 0], // 用于判断当前滑动的是哪一列
			province: [], // 数据列表
			imgArr: [],
			isDis: false,
			class1: "",
			class2: "",
			class3: "",
			uid: "",
			typeFirstID: "",
			typeFirstName: "",
			typeSecondID: "",
			typeSecondName: "",
			typeThirdID: "",
			typeThirdName: "",
			content: "",
			lon: "",
			lat: "",
			title: "",
			typeId: 0, //1 图片 2 视频3附件
			items: [{
				value: "1",
				name: "图片"
			}, {
				value: "2",
				name: "视频"
			}, {
				value: "3",
				name: "附件"
			}],
			current: "",
			rules: {
				title: {
					msg: '请输入题目'
				},
				class3: {
					msg: '请选取分类'
				},
				address: {
					msg: '请选取地图位置标注'
				},
				content: {
					msg: '请输入描述'
				},
			},
		};
	},
	methods: {
		radioChange: function(evt) {
			for(let i = 0; i < this.items.length; i++) {
				if(this.items[i].value == evt.target.value) {
					this.typeId = this.items[i].value;
					this.imgArr = [];
					break;
				}
			}
		},
		delImg(ind) {
			this.imgArr.splice(ind, 1);
		},
		inputChange(e) {
			let type = e.currentTarget.dataset.i;
			this[type] = e.detail.value;
		},
		subMit() {
			let rules = this.rules;
			for(let key in rules) {
				if(!this[key]) {
					uni.showToast({
						icon: "none",
						title: rules[key].msg,
					});
					return false;
				}
			}
			let data = {
				uid: this.uid,
				typeFirstID: this.class1.id,
				typeFirstName: this.class1.name,
				typeSecondID: this.class2.id,
				typeSecondName: this.class2.name,
				typeThirdID: this.class3.id,
				typeThirdName: this.class3.name,
				content: this.content,
				attr: this.imgArr.join(","),
				lon: this.lon,
				lat: this.lat,
				title: this.title,
				address: this.address,
				typeID: parseInt(this.typeId),

			}
			this.$set(this, "isDis", true);
			NetService.recWxsaverec(data)
				.then(res => {
					uni.showToast({
						title: "上报成功，为您返回上一页"
					});
					this.$set(this, "isDis", false);
					setTimeout(function() {
						uni.navigateBack();
					}, 1000);
				})
				.catch(err => {
					this.$set(this, "isDis", false);
				});
		},
		choseImg() {
			let _this = this;
			let current = this.typeId;
			if(_this.isDis) {
				return false;
			}
			if(current == 1) {
				if(this.imgArr.length >= 9) {
					uni.showToast({
						icon: "none",
						title: "图片只能上传9张"
					});
					return false;
				}

				uni.chooseImage({
					count: 9 - this.imgArr.length,
					success: function(res) {
						_this.$set(_this, "isDis", true);
						_this.upOk(res);
					}
				});
			} else if(current == 2) {
				if(this.imgArr.length >= 1) {
					uni.showToast({
						icon: "none",
						title: "视频只能上传一个"
					});
					return false;
				}
				uni.chooseVideo({
					count: 1,
					sourceType: ['camera', 'album'],
					success: function(res) {
						_this.$set(_this, "isDis", true);
						uni.uploadFile({
							url: '/webApi/upload', //仅为示例，非真实的接口地址
							filePath: res.tempFilePath,
							name: 'file',
							formData: {},
							success: uploadFileRes => {
								_this.imgArr.push(JSON.parse(uploadFileRes.data).data);
							},
							complete: () => {
								_this.$set(_this, "isDis", false);

							}
						});
					}
				});
			} else if(current == 3) {
				if(this.imgArr.length >= 1) {
					if(this.imgArr.length >= 1) {
						uni.showToast({
							icon: "none",
							title: "附件只能上传一个"
						});
						return false;
					}
					return false;
				}
				uni.chooseFile({
					count: 1,
					extension: ['.docx', '.doc', '.doc', '.dotx', '.pdf', '.xls', '.xlsx'],
					success: res => {
						_this.$set(_this, "isDis", true);
						_this.upOk(res);
					}
				});
			}
		},
		upOk(res) {
			let _this = this;
			const tempFilePaths = res.tempFilePaths;
			tempFilePaths.forEach(item => {
				uni.uploadFile({
					url: '/webApi/upload', //仅为示例，非真实的接口地址
					filePath: item,
					name: 'file',
					formData: {},
					success: uploadFileRes => {
						_this.imgArr.push(JSON.parse(uploadFileRes.data).data);
					},
					complete: () => {
						_this.$set(_this, "isDis", false);
					}
				});
			})
		},
		toTree(data) {
			let result = [];
			if(!Array.isArray(data)) {
				return result;
			}
			data.forEach(item => {
				delete item.children;
			});
			let map = {};
			data.forEach(item => {
				map[item.id] = item;
			});
			data.forEach(item => {
				let parent = map[item.pid];
				if(parent) {
					(parent.children || (parent.children = [])).push(item);
				} else {
					result.push(item);
				}
			});
			return result;
		},
		init() {
			let u = uni.getStorageSync('user');
			if(u) {
				this.uid = u.userID;
			}
			NetService.getcatepidtree()
				.then(res => {
					let n = this.toTree(res);
					console.log(n);
					this.province = n;
				})
				.catch(err => {});
	/*		let routes = window.location.href
			NetService.wxConfig(routes)
				.then(res => {
					jweixin.config({
						debug: false,
						appId: res.app_id,
						timestamp: res.timestamp,
						nonceStr: res.nonce_str,
						signature: res.signature,
						jsApiList: ["getLocation"]
					});
				})
				.catch(err => {});*/
		},
		bindChange(e) {
			const val = e.detail.value;
			if(this.valueArr[0] !== val[0]) {
				this.loadCity(this.province[val[0]].id);
			} else if(this.valueArr[1] !== val[1]) {
				this.loadArea(this.province[val[0]].children[val[1]].id);
			}
			console.log('val', val);
			this.valueArr = val;
		},
		getItem(id) {
			let obj;

			function seach(arr) {
				arr.forEach(item => {
					if(item.id == id) {
						obj = item;
					} else {
						if(item.children && item.children.length > 0) {
							seach(item.children);
						}
					}
				});
			}
			seach(this.province);
			return obj;
		},
		loadCity(parentId) {
			console.log('getItem', this.getItem(parentId));
			let data = this.getItem(parentId);
			if(this.province[this.valueArr[0]].children === undefined) {
				this.$set(this.province[this.valueArr[0]], 'children', []);
				data.forEach(item => {
					this.province[this.valueArr[0]].children.push(item);
				});
				this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].id);
			}
		},
		loadArea(parentId) {
			let data = this.getItem(parentId);
			if(this.province[this.valueArr[0]].children[this.valueArr[1]].children === undefined) {
				this.$set(this.province[this.valueArr[0]].children[this.valueArr[1]], 'children', []);
				data.forEach(item => {
					this.province[this.valueArr[0]].children[this.valueArr[1]].children.push(item);
				});
			}
		},
		toggleTab() {
			this.$refs.popup.open();
		},
		cancel() {
			this.$refs.popup.close();
		},
		confirm() {
			this.$refs.popup.close();
			console.log(this.valueArr);
			this.province.forEach((item, index) => {
				if(index == this.valueArr[0]) {
					this.class1 = item;
					if(item.children.length > 0) {
						item.children.forEach((ite, ind) => {
							if(ind == this.valueArr[1]) {
								this.class2 = ite;
								if(ite.children.length > 0) {
									ite.children.forEach((it, i) => {
										if(i == this.valueArr[2]) {
											this.class3 = it;
										}
									})
								}
							}
						})
					}
				}
			});
			console.log(this)

		},
		AttrJump(url) {
			window.location.href = url
		},
		mapChage() {
			let _this = this;
			uni.getLocation({
				type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success: function(r) {
					console.log("r", r)
					uni.chooseLocation({
						latitude: r.latitude,
						longitude: r.longitude,
						success: function(res) {
							_this.address = res.address;
							_this.lon = res.latitude;
							_this.lat = res.longitude;
							console.log('位置名称：' + res.name, _this.address);
							console.log('详细地址：' + res.address);
							console.log('纬度：' + res.latitude);
							console.log('经度：' + res.longitude);
						}
					});
				}
			});
			/*jweixin.ready(function() {
						jweixin.getLocation({
							type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
							success: function(r) {
								console.log("r", r)
								uni.chooseLocation({
									latitude: r.latitude,
									longitude: r.longitude,
									success: function(res) {
										_this.address = res.address;
										_this.lon = res.latitude;
										_this.lat = res.longitude;
										console.log('位置名称：' + res.name, _this.address);
										console.log('详细地址：' + res.address);
										console.log('纬度：' + res.latitude);
										console.log('经度：' + res.longitude);
									}
								});
							}
						});
					});*/

		},
	},
	onLoad() {
		let _this = this;
		this.$getOpenId(() => {
			let u = uni.getStorageSync('user');
			if(!u.userID) {
				uni.showToast({
					icon: "none",
					title: "您未登陆绑定，请登陆"
				});
				setTimeout(function() {
					uni.navigateTo({
						url: "/pages/bind/bind"
					});
				}, 1000);
				return false;
			}
			_this.init();
			//#ifdef H5
			// 判断是否是微信内
			let en = window.navigator.userAgent.toLowerCase();
			// 匹配en中是否含有MicroMessenger字符串
			if(en.match(/MicroMessenger/i) == 'micromessenger') {
				_this.$share({
					title: "渝中网格化系统-案件上报"
				});
			}
			//#endif
		});
	}
};